import type { MenuDataItem } from "@/constants";
import { personalMenus } from "@/constants";
import { useMainStore } from "@/stores";
import { Breadcrumb } from "antd";
import { ItemType } from "antd/es/breadcrumb/Breadcrumb";
import { NavLink, useLocation } from "react-router-dom";
/**
 * 面包屑的数据：【兼容以下三种情况】
 * 1，属于左侧菜单，且正常显示。
 * 2，属于左侧菜单，但是不显示的详情页面。
 * 3, 不属于左侧菜单，一般为个人中心的部分页面。
 */

const Index: React.FC = () => {
  const { pathname } = useLocation();
  const { keyPath, menuList } = useMainStore((state) => state);

  // 判断是否为个人中心页面
  const isPersonalRoute = (path: string) => {
    // 取第一层菜单即可判断
    const str = path.split("/")[1];
    const result = personalMenus.some((item) => {
      return item.path.includes(str);
    });
    return result;
  };

  // 分解pathname【限定最多两级】
  const splitPath = (path: string) => {
    const paths = path.split("/");
    const firstPath = "/" + paths[1];
    if (paths.length === 2) {
      return [firstPath];
    }
    return [firstPath, path];
  };

  // 过滤菜单
  const filterBreadcrumbs = (
    arr: string[],
    menus: MenuDataItem[],
    index = 0,
    results: MenuDataItem[] = []
  ) => {
    menus.forEach((item: MenuDataItem) => {
      if (item.path === arr[index]) {
        results.push(item);
        if (arr[index + 1] && item.children && item.children.length > 0) {
          filterBreadcrumbs(arr, item.children, index + 1, results);
        }
      }
    });
    return results;
  };

  // 面包屑数据
  let items: ItemType[] = [];
  if (pathname === "/home") {
    items = [];
  } else {
    let pathItems: MenuDataItem[] = [];
    // 区分个人中心和普通左侧菜单
    if (isPersonalRoute(pathname)) {
      const paths = splitPath(pathname);
      pathItems = filterBreadcrumbs(paths, personalMenus);
    } else {
      pathItems = filterBreadcrumbs(keyPath, menuList);
    }
    items = pathItems.map((item) => {
      return {
        title: item.title
      };
    });
    items.unshift({ title: <NavLink to="/home">首页</NavLink> });
  }

  return <Breadcrumb items={items}></Breadcrumb>;
};

export default Index;
